package data
{
	import com.maclema.mysql.MySqlToken;
	import com.maclema.mysql.ResultSet;
	
	import controls.DataRequestor;
	import controls.events.ServiceEvent;
	
	import flash.events.EventDispatcher;
	import flash.utils.Dictionary;
	
	import mx.collections.ArrayCollection;
		
	public class ClassGroup extends EventDispatcher
	{
		public var creditsRequired:int;
		public var classes:Array;
		public var id:int;
		public var name:String;
		private var gpa_sum:Number;
		
		// ------------------- Private Variables ---------------- //
		private var requestor:DataRequestor = DataRequestor.instance;
		
		private var pendingRequests:int = 0;
		private var pending:Dictionary;
		// ------------------- END Private Variables ---------------- //
		
		public function ClassGroup(groupInfo:Object = null)
		{
			classes = [];
			name = "";
			gpa_sum = 0;
			pending = new Dictionary();
			
			if(groupInfo != null)
			{
				creditsRequired = groupInfo.numGroup;
				id = groupInfo.groupID;
				//name = groupInfo.groupName;
				getClassInformation();
			}
		}

		public function addCourse(course:Course):void
		{
			classes.push(course);
		}
		
		public function get gpa():Number
		{
			var count:int = 0;
			var gpa:Number = 0;
			for each(var course:Course in classes)
			{	
				if(!isNaN(course.gpa))
				{
					count ++;
					gpa += course.gpa;
				}
			}
			return gpa / count;
		}
		
		// ------------------ Data Fetching and Parsing -------------------- //
		public function getClassInformation():void
		{
			requestor.getClassGroup(this, parseClassGroup);
		}
		
		private function parseClassGroup(sqlData:Object, token:MySqlToken):void
		{
			var rs:ResultSet = sqlData as ResultSet;
			
			var rows:ArrayCollection = rs.getRows();
			pendingRequests = rows.length;
			
			for each(var row:Object in rs.getRows())
			{
				var course:Course = new Course(row);
				course.addEventListener(ServiceEvent.COURSES_LOADED, onCoursesReady);
				this.addCourse(course);
				pending[course.id] = course;
			}
			this.name = row.groupName;
		}
		
		private function onCoursesReady(evt:ServiceEvent):void
		{
			var course:Course = evt.data as Course;
			if(!isNaN(course.gpa))
				gpa_sum += course.gpa;
			pendingRequests --;
			pending[course.id] = false;
			if(pendingRequests == 0)
				this.dispatchEvent(new ServiceEvent(ServiceEvent.PROGRAM_LOADED, this));
		}
		// ------------------ END Data Fetching and Parsing -------------------- //
	}
}